import os
from django import http
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
from alipay import AliPay
from apps.orders.models import OrderInfo
from apps.payment.models import Payment
from utils.response_code import RETCODE

# 订单支付功能

class PaymentView(LoginRequiredMixin, View):

    def get(self, request, order_id):
        # 检验订单是否存在
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except:
            return http.HttpResponseForbidden("订单无效")
        # 生成alipay支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None, #默认回调路由
            #os.path.join确认路径需要拼接  os.path.dirname上层目录==../   os.path.abspath(__file__)当前文件的绝对路径
            # app私钥地址
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "keys/app_private_key.pem"),
            # 支付宝公钥地址
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",   #加密方式
            debug=settings.ALIPAY_DEBUG     #开发环境
        )
        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  #订单id
            total_amount=str(order.total_amount),       #总金额
            subject= "美多商城的订单%s" % order_id,    #订单抬头
            return_url=settings.ALIPAY_RETURN_URL,      #回调地址
        )
        # 返回给前端     # 将必传的参数进行加密拼接url
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})

# 展示支付完成页面

class PaymentSucessView(LoginRequiredMixin, View):
    def get(self,requset):
        # 接收查询参数    下三步为固定写法
        params_query_dict = requset.GET
        # 类型强制转换querydict---dict
        data = params_query_dict.dict()
        # 删除参数中的    pop（'sign'）
        signature = data.pop('sign')
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 支付宝二次校验
        # 校验这个重定向是否是alipay重定向过来的
        success = alipay.verify(data, signature)
        # 获取订单号和交易id---持久话到  表里
        if success:
            # 读取order_id
            order_id = data.get('out_trade_no')
            # 读取支付宝流水号
            trade_id = data.get('trade_no')
            # 保存Payment模型类数据
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )
        # 更改状态为待评价
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])
        # 返回响应
            context = {
                'trade_id': trade_id
        }
            return render(requset, 'pay_success.html', context)
        else:
            # 订单支付失败，重定向到我的订单
            return http.HttpResponseForbidden('非法请求')
